/* 路由 */
const router = require("koa-router")();

const DB = require("../../module/db.js");

const tools = require("../../module/tools.js");

router.get("/", async (ctx) => {
  let result = await DB.find("nav", {});

  await ctx.render("admin/nav/list", {
    list: result,
  });
});

router.get("/addNav", async (ctx) => {
  await ctx.render("admin/nav/add");
});

//执行增加操作
router.post("/doAddNav", async (ctx) => {
  //接受数据
  console.log(ctx.req.body);
  let title = ctx.request.body.title;

  let url = ctx.request.body.url;

  let status = parseInt(ctx.request.body.status);

  let add_time = tools.getTime();

  await DB.insert("nav", { title, url, status, add_time });

  //跳转
  ctx.redirect(ctx.state.__HOST__ + "/admin/nav");
});

router.get("/editNav", async (ctx) => {
  let id = ctx.query.id;

  let result = await DB.find("nav", { _id: DB.getObjectId(id) });

  await ctx.render("admin/nav/edit", {
    list: result[0],
    prevPage: ctx.state.G.prevPage,
  });
});

router.post("/doEditNav", async (ctx) => {
  let id = ctx.request.body.id;

  let title = ctx.request.body.title;

  let url = ctx.request.body.url;

  let status = ctx.request.body.status;

  let prevPage = ctx.request.body.prevPage;

  let add_time = tools.getTime();

  await DB.update(
    "nav",
    { _id: DB.getObjectId(id) },
    { title, url, status, add_time }
  );

  //跳转
  if (prevPage) {
    ctx.redirect(prevPage);
  } else {
    //跳转
    ctx.redirect(ctx.state.__HOST__ + "/admin/nav");
  }
});

module.exports = router.routes();
